<?php

namespace App\Repositories;

use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;
use App\Services\Tools\HelperService;
use phpDocumentor\Reflection\PseudoTypes\True_;

use function Matrix\add;

//引入hash

class AccountLogRepository
{
    /**
     * 更新提现资金记录
     *
     * @param $id
     * @return bool
     */
    public function saveWithDrawLog($id)
    {
        $saveWithDraw = app('model_account_log')->where(['source_id' => $id, 'change_type' => 23])->update(['change_desc' => '提现已到账', 'change_type' => 2]);

        return $saveWithDraw;
    }

    /**
     * 更新提现资金退回记录
     *
     * @param $id
     * @return bool
     */
    public function saveWithDrawRefundLog($id)
    {
        $saveWithDraw = app('model_account_log')->where(['source_id' => $id, 'change_type' => 23])->update(['change_desc' => '已退回', 'change_type' => 24]);

        return $saveWithDraw;
    }

    /**
     * 新增日志
     *
     * @param  $param
     * @return bool
     * @throws BasicException
     */
    public function addLog($param)
    {
        $add = app('model_account_log')->create($param);
        if ($add) {
            return $add;
        }
        throw new BasicException(93132);
    }

    /**
     * 新增变更日志
     *
     * @param  $param
     * @return bool
     * @throws BasicException
     */
    public function addAccountLog($user_id, $user_money, $change_desc, $change_type, $room_id = 0, $popularity = 0, $source_id = 0)
    {
        $data['user_id'] = $user_id;
        $data['user_money'] = $user_money;
        $data['change_time'] = time();
        $data['change_desc'] = $change_desc;
        $data['change_type'] = $change_type;
        $data['room_id'] = $room_id;
        $data['popularity'] = $popularity;
        $data['source_id'] = $source_id;

        $newAccountLog = app('model_account_log')->create($data);
        if (!$newAccountLog) {
            throw new BasicException(93132);
        }

        return $newAccountLog;
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getUserAccountLogQueryList(array $params)
    {
        $accountType = $params['account_type'] ?? '';
        $happenTimeStart = $params['happen_time_start'] ?? '';
        $happenTimeEnd = $params['happen_time_end'] ?? '';

        if ($happenTimeStart && $happenTimeEnd) {
            if (strtotime($happenTimeEnd) - strtotime($happenTimeStart) > 31 * 86400) {
                throw new BasicException(0, '时间跨度不能超过31天');
            }
        }

        switch ($accountType) {
            case 1: //余额日志
                $model = app('model_account_money_log');
                break;
            case 2: //收益日志
                $model = app('model_account_earnings_log');
                break;
            case 3: //全部日志
                return $this->getUserAllAccountLogQueryList($params);
                break;
        }

        $where = [];
        if (!empty($params['nickname'])) {
            $userId = app('model_user_data')->where('nickname', $params['nickname'])->value('user_id');
            $where[] = ['user_id', '=', $userId];
        }
        if (isset($params['user_code'])) {
            $userId = app('model_user_data')->where('user_code', $params['user_code'])->value('user_id');
            $where[] = ['user_id', '=', $userId];
        }
        if (!empty($params['mobile'])) {
            $userId = app('model_user')->where('mobile', $params['mobile'])->where('deleted', 0)->value('user_id');
            $where[] = ['user_id', '=', $userId];
        }
        if (!empty($params['change_type'])) {
            $where[] = ['change_type', '=', $params['change_type']];
        }
        if ($happenTimeStart) {
            //            if ($accountType != 1) {
            //                $where[] = ['created_at', '>=', strtotime($happenTimeStart)];
            //            }
            $where[] = ['created_at', '>=', $happenTimeStart];
        }
        if ($happenTimeEnd) {
            //            if ($accountType != 1) {
            //                $where[] = ['created_at', '<=', strtotime($happenTimeEnd)];
            //            }
            $where[] = ['created_at', '<=', $happenTimeEnd];
        }
        if (empty($where)) {
            throw new BasicException(0, '请选择查询条件');
        }

        $data = $model
            ->select([
                'id',
                'user_id',
                'change_type',
                'change_desc',
                'change_money',
                'created_at'
            ])
            ->where($where)
            ->orderBy('id', 'desc')
            ->limit(65536)
            ->get()->each(function ($item) {
                $item->user_money = $item->change_money;
                $item->change_time = $item->created_at;
            })
            ->toArray();
        if (count($data) > 65535) {
            throw new BasicException(0, '导出数据量过大(最多65535)，请重新设置筛选条件');
        }

        //批量查询用户数据
        $userIds = array_column($data, 'user_id');
        $userIdsArr = array_chunk($userIds, 1000);

        $users = $userDatas = [];
        foreach ($userIdsArr as $userIdArr) {
            $userChunk = app('model_user')
                ->whereIn('user_id', array_unique($userIdArr))->where('deleted', 0)
                ->pluck('mobile', 'user_id')->toArray();
            $users += $userChunk;

            $userDataChunk = app('model_user_data')
                ->select('user_id', 'user_code', 'nickname')
                ->whereIn('user_id', $userIdArr)
                ->get()->toArray();
            $userDatas += array_column($userDataChunk, null, 'user_id');
        }

        //类型id与名称的映射
        $type_list = app('repo_account_log')->typeList();
        $type_list_arr = [];
        foreach ($type_list as $val) {
            $type_list_arr[$val['change_type']] = $val['name'];
        }

        foreach ($data as &$v) {
            $v['change_time'] = empty($v['change_time']) ? '' : $v['change_time'];
            $v['change_type_name'] = $type_list_arr[$v['change_type']];
            if (isset($users[$v['user_id']])) {
                $v['mobile'] = $users[$v['user_id']];
            } else {
                $v['mobile'] = '';
            }
            if ($v['change_desc']) {
                $v['change_desc'] = HelperService::wxNickNameFormat($v['change_desc']);
            }
            if (isset($userDatas[$v['user_id']])) {
                $v['user_code'] = $userDatas[$v['user_id']]['user_code'];
                $v['nickname'] = HelperService::wxNickNameFormat($userDatas[$v['user_id']]['nickname']);
            } else {
                $v['user_code'] = '';
                $v['nickname'] = '';
            }
            if ($v['nickname'] && strpos($v['nickname'], '=') === 0) {
                $v['nickname'] = "'" . $v['nickname'];
            }
        }

        return $data;
    }

    //获取用户收支日志
    public function getUserAccountLog(array $params)
    {
        $accountType = $params['account_type'];
        $userCode = $params['user_code'] ?? 0;
        $nickname = $params['nickname'] ?? 0;
        $mobile = $params['mobile'] ?? 0;
        $changeType = $params['change_type'] ?? 0;
        $page = $params['page'] ?? 1;
        $perPage = $params['perPage'] ?? 10;
        $happenTimeStart = $params['happen_time_start'] ?? '';
        $happenTimeEnd = $params['happen_time_end'] ?? '';

        if ($accountType == 1) {
            $model = app('model_account_money_log');
        } else {
            $model = app('model_account_earnings_log');
        }

        $where = $whereFunc = [];
        if ($userCode) {
            $userId = app('model_user_data')->where('user_code', $userCode)->value('user_id');
            $where[] = ['user_id', '=', $userId];
        }
        if ($nickname) {
            $userIds = app('model_user_data')->select('user_id')->where('nickname', 'like', '%' . $nickname . '%')->pluck('user_id')->toArray();
            $whereFunc = function ($query) use ($userIds) {
                $query->whereIn('user_id', $userIds);
            };
        }
        if ($mobile) {
            $userId = app('model_user')->where('mobile', $mobile)->value('user_id');
            $where[] = ['user_id', '=', $userId];
        }
        if ($changeType) {
            $where[] = ['change_type', '=', $changeType];
        }
        if ($happenTimeStart) {
            $where[] = ['created_at', '>=', $happenTimeStart];
        }
        if ($happenTimeEnd) {
            $where[] = ['created_at', '<=', $happenTimeEnd];
        }

        $fields = ['id', 'user_id', 'change_money', 'change_type', 'change_desc', 'created_at'];
        if ($where || $whereFunc) {
            $list = $model
                ->select($fields)
                ->where($where)
                ->where($whereFunc)
                ->orderByDesc('id')->paginate($perPage)->toArray();
            $data = $list['data'];
        } else {
            $minId = $model->min('id');
            $maxId = $model->max('id');
            $endId = $maxId - ($page - 1) * $perPage;
            $startId = $endId - $perPage;

            $where2 = [['id', '>', $startId], ['id', '<=', $endId]];

            $list['total'] = $maxId - $minId + 1;

            $data = $model->select($fields)->where($where2)->orderByDesc('id')->get()->toArray();
        }

        $userIds = array_unique(array_column($data, 'user_id'));
        $users = app('model_user')->whereIn('user_id', $userIds)->pluck('mobile', 'user_id');
        $userDatas = app('model_user_data')->whereIn('user_id', $userIds)->get()->keyBy('user_id')->toArray();

        //类型id与名称的映射
        $type_list = app('repo_account_log')->typeList();
        $type_list_arr = [];
        foreach ($type_list as $key => $val) {
            $type_list_arr[$val['change_type']] = $val['name'];
        }

        foreach ($data as &$v) {
            $v['change_type_name'] = $type_list_arr[$v['change_type']] ?? '';
            if (isset($users[$v['user_id']])) {
                $v['mobile'] = $users[$v['user_id']];
            } else {
                $v['mobile'] = '';
            }
            if (isset($userDatas[$v['user_id']])) {
                $v['user_code'] = $userDatas[$v['user_id']]['user_code'];
                $v['nickname'] = $userDatas[$v['user_id']]['nickname'];
            } else {
                $v['user_code'] = '';
                $v['nickname'] = '';
            }
        }
        if (isset($where)) {
            $list['data'] = $data;
        }

        if ($changeType) {
            if (count($where) == 1 && empty($whereFunc)) {
                $list['sum_coin'] = '除类别外请再选择一个筛选条件';
            } else {
                $list['sum_coin'] = $model->where($where)->where($whereFunc)->sum('change_money');
                $list['sum_coin'] = round($list['sum_coin'], 2);
            }
        } else {
            $list['sum_coin'] = '请选择类别';
        }

        return $list;
    }

    public function typeList()
    {
        return app('model_user_account_change_type')->select('id as change_type', 'name')->get()->toArray();
    }

    public function getAdminRechargeQueryList($params)
    {
        $start_time = isset($params['start_time']) ? strtotime($params['start_time']) : 0;
        $end_time = isset($params['end_time']) ? strtotime($params['end_time'] . ' 23:59:59') : 0;

        //用户总充值
        $whereFunc = function ($query) use ($start_time, $end_time) {
            if ($start_time) {
                $query->whereRaw(DB::raw('change_time >= {$start_time}'));
            }
            if ($end_time) {
                $query->whereRaw(DB::raw('change_time <= {$end_time}'));
            }

            $query->whereRaw(DB::raw('change_type = 21'));
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $subQuery = app('model_account_log')
            ->select(
                DB::raw('from_unixtime(change_time,"%Y-%m-%d") as change_time'),
                DB::raw('sum(user_money) money')
            )
            ->groupBy(DB::raw('from_unixtime(change_time, "%Y-%m-%d")'))
            ->where($whereFunc);

        $result = DB::connection('mysql')->table(DB::raw('({$subQuery->toSql()}) as t1'))
            ->setBindings(['1', '2', '3', '4', '5', '6'])
            ->orderBy('t1.change_time', 'desc')
            ->paginate($perPage, ['*'], '', $page);


        return $result;
    }

    public function getAllUserAccountLog($params = [], $export_page_info = [])
    {
        $userCode = $params['user_code'] ?? 0;
        $nickname = $params['nickname'] ?? 0;
        $mobile = $params['mobile'] ?? 0;
        $page = $params['page'] ?? 1;
        $perPage = $params['perPage'] ?? 10;
        $happenTimeStart = $params['happen_time_start'] ?? '';
        $happenTimeEnd = $params['happen_time_end'] ?? '';
        $page_type =  $params['page_type'] ?? 1;
        $page_info =  $params['page_info'] ?? '';
        $changeType = $params['change_type'] ?? 0;
        $page_pre_info = $params['page_pre_info'] ?? '';

        $where = $whereFunc = $giftWhere = [];
        if ($userCode) {
            $userId = app('model_user_data')->where('user_code', $userCode)->value('user_id');
            $where[] = ['user_id', '=', $userId];
        }
        if (!empty($nickname)) {
            $userIds = app('model_user_data')->select('user_id')->where('nickname', 'like', '%' . $nickname . '%')->pluck('user_id')->toArray();
            $whereFunc = function ($query) use ($userIds) {
                $query->whereIn('user_id', $userIds);
            };
        }
        if ($mobile) {
            $userId = app('model_user')->where('mobile', $mobile)->value('user_id');
            $where[] = ['user_id', '=', $userId];
        }
        $giftWhere = $where;
        if ($happenTimeStart) {

            $giftWhere[] = ['add_time', '>=', strtotime($happenTimeStart)];
            $where[] = ['created_at', '>=', $happenTimeStart];
        }
        $giftWhere = $giftWhere;
        if ($happenTimeEnd) {
            $giftWhere[] = ['add_time', '<=', strtotime($happenTimeEnd)];
            $where[] = ['created_at', '<=', $happenTimeEnd];
        }
        $totalWhere = $where;
        if ($changeType) {
            $where[] = ['change_type', '=', $changeType];
        }

        $moneyModel = app('model_account_money_log');
        $earningModel = app('model_account_earnings_log');
        $givegiftModel = app('model_give_gift');

        $isfirstPage = '<';


        $page_str_arr = explode("|", $page_info);
        $page_pre_arr = explode("|", $page_pre_info);

        if (!empty($page_info) && !empty($page_str_arr) && is_array($page_str_arr)) {
            // $page_arr = json_decode($page_info, true);
            $page_arr['money_max_id'] = $page_str_arr[0];
            $page_arr['earning_max_id'] = $page_str_arr[1];
            $page_arr['givegift_max_id'] = $page_str_arr[2];
        } else {
            $isfirstPage = '<=';
            $page_arr['money_max_id'] =  $moneyModel->where($where)
                ->where($whereFunc)->max('id') ?? 0;
            $page_arr['earning_max_id'] =  $earningModel->where($where)
                ->where($whereFunc)->max('id') ?? 0;
            $page_arr['givegift_max_id'] =  $givegiftModel->where($giftWhere)
                ->where($whereFunc)->where(['type' => 5])->max('id') ?? 0;
        }

        if ($page_type == 2 && !empty($page_pre_info) && !empty($page_pre_arr) && is_array($page_pre_arr)) {
            $page_arr['money_max_id'] = $page_pre_arr[0];
            $page_arr['earning_max_id'] = $page_pre_arr[1];
            $page_arr['givegift_max_id'] = $page_pre_arr[2];

            $money_max_id =  $moneyModel->where($where)
                ->where($whereFunc)->max('id');
            $earning_max_id =  $earningModel->where($where)
                ->where($whereFunc)->max('id');
            $givegift_max_id =  $givegiftModel->where($giftWhere)
                ->where($whereFunc)->where(['type' => 5])->max('id');

            if ($money_max_id == $page_arr['money_max_id'] && $earning_max_id == $page_arr['earning_max_id'] && $givegift_max_id == $page_arr['givegift_max_id']) {
                $isfirstPage = ">=";
            } else {
                $isfirstPage = ">";
            }
        }




        if (!empty($export_page_info)) {
            $page_arr = $export_page_info;
            $isfirstPage = '<=';
        }

        $endMoneyId =  $page_arr['money_max_id'];

        $startMoneyId = $page_type == 1 ? $endMoneyId - $perPage : $endMoneyId + $perPage;
        if (!empty($where) || !empty($whereFunc)) {
            $endWhere = $page_type == 1 ? [['id', $isfirstPage, $endMoneyId]] : [['id', $isfirstPage, $endMoneyId]];
            $startMoneyArr = $moneyModel->where($where)
                ->where($whereFunc)->where($endWhere)->limit($perPage)->orderBy("id", 'desc')->get()->toarray();
            $startMoneyId = $startMoneyArr[count($startMoneyArr) - 1]['id'] ?? $endMoneyId;
        }

        $where_money = $page_type == 1 ? [['id', '>=', $startMoneyId], ['id', $isfirstPage, $endMoneyId]] : [['id', $isfirstPage, $endMoneyId], ['id', '<=', $startMoneyId]];

        $moneyData = $moneyModel
            ->select("*")
            ->where($where_money)
            ->where($where)
            ->where($whereFunc)
            ->orderByDesc('id')
            ->get()
            ->toArray();

        foreach ($moneyData as  &$value) {
            $value['arr_type'] = 1;
            $value['gift_user'] = 0;
        }

        //收益日志
        $endEarningId = $page_arr['earning_max_id'];
        $startEarningId = $page_type == 1 ? $endEarningId - $perPage : $endEarningId + $perPage;
        if (!empty($where) || !empty($whereFunc)) {
            $endWhere = $page_type == 1 ? [['id', $isfirstPage, $endEarningId]] : [['id', $isfirstPage, $endEarningId]];
            $startEarningArr = $earningModel->where($where)
                ->where($whereFunc)->where($endWhere)->limit($perPage)->orderBy("id", 'desc')->get()->toarray();
            $startEarningId = $startEarningArr[count($startEarningArr) - 1]['id'] ?? $endEarningId;
        }

        $where_earning = $page_type == 1 ? [['id', '>=', $startEarningId], ['id', $isfirstPage, $endEarningId]] : [['id', $isfirstPage, $endEarningId], ['id', '<=', $startEarningId]];
        $earningData = $earningModel
            ->select("*")
            ->where($where_earning)
            ->where($where)
            ->where($whereFunc)
            ->orderByDesc('id')
            ->get()
            ->toArray();

        foreach ($earningData as  &$value) {
            $value['arr_type'] = 2;
            $value['gift_user'] = 0;
        }
        //礼物日志
        $giveGiftData = [];
        $endGiveGiftId = $page_arr['givegift_max_id'];
        if (empty($changeType) || (!empty($changeType) && $changeType == 9)) {


            $startGiveGiftId = $page_type == 1 ? $endGiveGiftId - $perPage : $endGiveGiftId + $perPage;
            $startGiveGiftArr = $givegiftModel->where($giftWhere)
                ->where($whereFunc)->where(['type' => 5])->limit($perPage)->orderBy("id", 'desc')->get()->toarray();
            $startGiveGiftId = $startGiveGiftArr[count($startGiveGiftArr) - 1]['id'] ?? 0;
            if (!empty($giftWhere) || !empty($whereFunc)) {
                $endWhere = $page_type == 1 ? [['id', $isfirstPage, $endGiveGiftId]] : [['id', '>', $endGiveGiftId]];
                $startGiveGiftArr = $givegiftModel->where($giftWhere)
                    ->where($whereFunc)->where($endWhere)->where(['type' => 5])->limit($perPage)->orderBy("id", 'desc')->get()->toarray();
                $startGiveGiftId = $startGiveGiftArr[count($startGiveGiftArr) - 1]['id'] ?? 0;
            }

            $where_givegift = $page_type == 1 ? [['id', '>=', $startGiveGiftId], ['id', $isfirstPage, $endGiveGiftId]] : [['id', $isfirstPage, $endGiveGiftId], ['id', '<=', $startGiveGiftId]];
            $giveGiftData = $givegiftModel
                ->select('id', "user_id", "total_price as change_money", "type as change_desc", "gift_user", "org_gift_id as source_id", "gift_user", DB::raw('from_unixtime(add_time) as created_at'))
                ->where($where_givegift)
                ->where(['type' => 5])
                ->where($giftWhere)
                ->where($whereFunc)
                ->orderByDesc('id')
                ->get()
                ->toArray();

            foreach ($giveGiftData as  &$value) {
                $value['arr_type'] = 3;
            }
        }

        $data = array_merge($moneyData, $earningData, $giveGiftData);

        usort($data, function ($a, $b) {
            $al = $a['created_at'];
            $bl = $b['created_at'];
            if ($al == $bl)
                return 0;
            return ($al > $bl) ? -1 : 1;
        });

        $page_info = $page_arr;
        $resList = [];
        if ($page_type == 1) {
            foreach ($data as $key => $dvalue) {

                if ($key >= $perPage) {
                    break;
                }
                if ($dvalue['arr_type'] == 1) {
                    $page_info['money_max_id'] = $dvalue['id'];
                }
                if ($dvalue['arr_type'] == 2) {
                    $page_info['earning_max_id'] = $dvalue['id'];
                }
                if ($dvalue['arr_type'] == 3) {
                    $page_info['givegift_max_id'] = $dvalue['id'];
                }
                $resList[] = $dvalue;
            }
            $page_pre_info = implode("|", [$endMoneyId, $endEarningId, $endGiveGiftId]);
        } else {
            $tem_arr = [];

            $data = array_slice($data, -$perPage);

            $page_pre_info = $page_arr;
            foreach ($data as $key => $tvalue) {
                if ($tvalue['arr_type'] == 1) {
                    $page_info['money_max_id'] = $tvalue['id'];
                }
                if ($tvalue['arr_type'] == 2) {
                    $page_info['earning_max_id'] = $tvalue['id'];
                }
                if ($tvalue['arr_type'] == 3) {
                    $page_info['givegift_max_id'] = $tvalue['id'];
                }
                if (empty($tem_arr['money_max_id']) && $tvalue['arr_type'] == 1) {
                    $page_pre_info['money_max_id'] = $tem_arr['money_max_id'] = $tvalue['id'];
                }
                if (empty($tem_arr['earning_max_id']) && $tvalue['arr_type'] == 2) {
                    $page_pre_info['earning_max_id'] = $tem_arr['earning_max_id'] = $tvalue['id'];
                }
                if (empty($tem_arr['givegift_max_id']) && $tvalue['arr_type'] == 3) {
                    $page_pre_info['givegift_max_id'] = $tem_arr['givegift_max_id'] = $tvalue['id'];
                }
                $resList[] = $tvalue;
            }

            $page_pre_info = implode('|', array_values($page_pre_info));
        }

        $data = $resList;

        if ($page_type == 2 && count($data) < $perPage) {
            $params['page_info'] = '';
            $params['page_type'] = 1;
            return $this->getAllUserAccountLog($params);
        }

        //获取礼物信息
        $giftIds = [];
        $giftUserIds = [];
        foreach ($data as $gvalue) {
            if ($gvalue['gift_user'] > 0) {
                $giftIds[] = $gvalue['source_id'];
                $giftUserIds[] = $gvalue['gift_user'];
            }
        }
        $giftInfo = app('model_gift')->whereIn('id', $giftIds)->pluck('name', 'id')->toarray();

        //获取用户信息
        $userIds = array_column($data, 'user_id');
        $userIds = array_unique(array_merge($userIds, $giftUserIds));
        $users = app('model_user')->whereIn('user_id', $userIds)->pluck('mobile', 'user_id')->toarray();
        $userDatas = app('model_user_data')->whereIn('user_id', $userIds)->get()->keyBy('user_id')->toArray();



        //类型id与名称的映射
        $type_list = app('repo_account_log')->typeList();
        $type_list_arr = [];
        foreach ($type_list as $key => $val) {
            $type_list_arr[$val['change_type']] = $val['name'];
        }

        $sumCoin = 0;
        foreach ($data as &$v) {

            if (in_array($v['arr_type'], [1, 2])) {
                $v['change_type_name'] = $type_list_arr[$v['change_type']] ?? '';
                if (isset($users[$v['user_id']])) {
                    $v['mobile'] = $users[$v['user_id']];
                } else {
                    $v['mobile'] = '';
                }
                if (isset($userDatas[$v['user_id']])) {
                    $v['user_code'] = $userDatas[$v['user_id']]['user_code'];
                    $v['nickname'] = $userDatas[$v['user_id']]['nickname'];
                } else {
                    $v['user_code'] = '';
                    $v['nickname'] = '';
                }
            } else {
                if (!isset($giftInfo[$v['source_id']])) {
                    $gift_name = '';
                } else {
                    $gift_name = $giftInfo[$v['source_id']];
                }
                $v['change_desc'] = "送给 " . $userDatas[$v['gift_user']]['nickname'] . " " . $gift_name;
                $v['change_type_name'] = "赠送背包礼物";
                if (isset($users[$v['user_id']])) {
                    $v['mobile'] = $users[$v['user_id']];
                } else {
                    $v['mobile'] = '';
                }
                if (isset($userDatas[$v['user_id']])) {
                    $v['user_code'] = $userDatas[$v['user_id']]['user_code'];
                    $v['nickname'] = $userDatas[$v['user_id']]['nickname'];
                } else {
                    $v['user_code'] = '';
                    $v['nickname'] = '';
                }
            }

            $sumCoin += $v['change_money'];
        }



        $list['data'] = $data;
        // $list['page_info'] = json_encode($page_info, 256);
        $list['page_info'] = implode('|', array_values($page_info));
        $list['page_info_arr'] = $page_info;

        $list['page_pre_info'] = $page_pre_info;



        $total = 0;
        $totalgiveGift = 0;
        if (empty($changeType) || (!empty($changeType) && $changeType == 9)) {
            $totalgiveGift = $givegiftModel->where(['type' => 5])
                ->where($giftWhere)
                ->where($whereFunc)
                ->count();
        }
        if (empty($where) && empty($whereFunc)){
            $total = 0;
        }else {
            $totalMoney = $moneyModel->where($where)
                ->where($whereFunc)->count();
            $totalEarning = $earningModel->where($where)
                ->where($whereFunc)->count();
            $total = $totalMoney + $totalEarning + $totalgiveGift;
        }
        $list['total'] = $total;


        if (empty($changeType)) {
            $sumCoin = "请选择类别";
        } elseif (empty($totalWhere) && empty($whereFunc)) {
            $sumCoin = "除类别外请再选择一个筛选条件";
        } else {
            $totalgiveGift = 0;
            if (empty($changeType) || (!empty($changeType) && $changeType == 9)) {
                $totalgiveGift = $givegiftModel->where(['type' => 5])
                    ->where($giftWhere)
                    ->where($whereFunc)
                    ->sum('total_price');
            }
            $totalMoney = $moneyModel->where($where)
                ->where($whereFunc)->sum('change_money');
            $totalEarning = $earningModel->where($where)
                ->where($whereFunc)->sum('change_money');
            $sumCoin =  $totalMoney + $totalEarning + $totalgiveGift;
        }
        // $sumCoin .= " 共有" . $total . "条数";

        $list['sum_coin'] = $sumCoin;

        return $list;
    }

    public function getUserAllAccountLogQueryList($params)
    {
        $userCode = $params['user_code'] ?? 0;
        $nickname = $params['nickname'] ?? 0;
        $mobile = $params['mobile'] ?? 0;
        $page = $params['page'] ?? 1;
        $perPage = $params['perPage'] ?? 50000;
        $happenTimeStart = $params['happen_time_start'] ?? '';
        $happenTimeEnd = $params['happen_time_end'] ?? '';
        $page_type =  $params['page_type'] ?? 1;
        $page_info =  $params['page_info'] ?? '';
        $changeType = $params['change_type'] ?? 0;


        $where = $whereFunc = $giftWhere = [];
        if ($userCode) {
            $userId = app('model_user_data')->where('user_code', $userCode)->value('user_id');
            $where[] = ['user_id', '=', $userId];
        }
        if (!empty($nickname)) {
            $userIds = app('model_user_data')->select('user_id')->where('nickname', 'like', '%' . $nickname . '%')->pluck('user_id')->toArray();
            $whereFunc = function ($query) use ($userIds) {
                $query->whereIn('user_id', $userIds);
            };
        }
        if ($mobile) {
            $userId = app('model_user')->where('mobile', $mobile)->value('user_id');
            $where[] = ['user_id', '=', $userId];
        }
        $giftWhere = $where;
        if ($happenTimeStart) {

            $giftWhere[] = ['add_time', '>=', strtotime($happenTimeStart)];
            $where[] = ['created_at', '>=', $happenTimeStart];
        }
        $giftWhere = $giftWhere;
        if ($happenTimeEnd) {
            $giftWhere[] = ['add_time', '<=', strtotime($happenTimeEnd)];
            $where[] = ['created_at', '<=', $happenTimeEnd];
        }
        $totalWhere = $where;
        if ($changeType) {
            $where[] = ['change_type', '=', $changeType];
        }

        $moneyModel = app('model_account_money_log');
        $earningModel = app('model_account_earnings_log');
        $givegiftModel = app('model_give_gift');


        $moneyData = $moneyModel
            ->select("*")
            // ->where($where_money)
            ->where($where)
            ->where($whereFunc)
            ->orderByDesc('id')
            ->limit(50000)
            ->get()
            ->toArray();

        foreach ($moneyData as  &$value) {
            $value['arr_type'] = 1;
            $value['gift_user'] = 0;
        }

        //收益日志
        $earningData = $earningModel
            ->select("*")
            // ->where($where_earning)
            ->where($where)
            ->where($whereFunc)
            ->orderByDesc('id')
            ->limit(50000)
            ->get()
            ->toArray();

        foreach ($earningData as  &$value) {
            $value['arr_type'] = 2;
            $value['gift_user'] = 0;
        }
        //礼物日志
        $giveGiftData = [];
        if (empty($changeType) || (!empty($changeType) && $changeType == 9)) {

            $giveGiftData = $givegiftModel
                ->select('id', "user_id", "total_price as change_money", "type as change_desc", "gift_user", "org_gift_id as source_id", "gift_user", DB::raw('from_unixtime(add_time) as created_at'))
                // ->where($where_givegift)
                ->where(['type' => 5])
                ->where($giftWhere)
                ->where($whereFunc)
                ->orderByDesc('id')
                ->limit(50000)
                ->get()
                ->toArray();

            foreach ($giveGiftData as  &$value) {
                $value['arr_type'] = 3;
            }
        }

        $data = array_merge($moneyData, $earningData, $giveGiftData);

        usort($data, function ($a, $b) {
            $al = $a['created_at'];
            $bl = $b['created_at'];
            if ($al == $bl)
                return 0;
            return ($al > $bl) ? -1 : 1;
        });


        $resList = [];
        if ($page_type == 1) {
            foreach ($data as $key => $dvalue) {

                if ($key >= $perPage) {
                    break;
                }
                $resList[] = $dvalue;
            }
        } else {
            $tem_arr = [];
            foreach ($data as $key => $tvalue) {
                if ($key >= $perPage) {
                    break;
                }
                $resList[] = $tvalue;
            }
        }

        $data = $resList;



        //获取礼物信息
        $giftIds = [];
        $giftUserIds = [];
        foreach ($data as $gvalue) {
            if ($gvalue['gift_user'] > 0) {
                $giftIds[] = $gvalue['source_id'];
                $giftUserIds[] = $gvalue['gift_user'];
            }
        }
        $giftInfo = app('model_gift')->whereIn('id', $giftIds)->pluck('name', 'id')->toarray();

        //获取用户信息
        $userIds = array_column($data, 'user_id');
        $userIds = array_unique(array_merge($userIds, $giftUserIds));
        $users = app('model_user')->whereIn('user_id', $userIds)->pluck('mobile', 'user_id')->toarray();
        $userDatas = app('model_user_data')->whereIn('user_id', $userIds)->get()->keyBy('user_id')->toArray();



        //类型id与名称的映射
        $type_list = app('repo_account_log')->typeList();
        $type_list_arr = [];
        foreach ($type_list as $key => $val) {
            $type_list_arr[$val['change_type']] = $val['name'];
        }

        $sumCoin = 0;
        foreach ($data as &$v) {

            if (in_array($v['arr_type'], [1, 2])) {
                $v['change_type_name'] = $type_list_arr[$v['change_type']] ?? '';
                if (isset($users[$v['user_id']])) {
                    $v['mobile'] = $users[$v['user_id']];
                } else {
                    $v['mobile'] = '';
                }
                if (isset($userDatas[$v['user_id']])) {
                    $v['user_code'] = $userDatas[$v['user_id']]['user_code'];
                    $v['nickname'] = HelperService::wxNickNameFormat($userDatas[$v['user_id']]['nickname']);
                } else {
                    $v['user_code'] = '';
                    $v['nickname'] = '';
                }
                if ($v['change_desc']) {
                    $v['change_desc'] = HelperService::wxNickNameFormat($v['change_desc']);
                }
            } else {
                if (!isset($giftInfo[$v['source_id']])) {
                    $gift_name = '';
                } else {
                    $gift_name = $giftInfo[$v['source_id']];
                }
                $v['change_desc'] = HelperService::wxNickNameFormat("送给 " . $userDatas[$v['gift_user']]['nickname'] . " " . $gift_name);
//                $v['change_desc'] = "送给 " . $userDatas[$v['gift_user']]['nickname'] . " " . $gift_name;
                $v['change_type_name'] = "赠送背包礼物";
                if (isset($users[$v['user_id']])) {
                    $v['mobile'] = $users[$v['user_id']];
                } else {
                    $v['mobile'] = '';
                }
                if (isset($userDatas[$v['user_id']])) {
                    $v['user_code'] = $userDatas[$v['user_id']]['user_code'];
//                    $v['nickname'] = $userDatas[$v['user_id']]['nickname'];
                    $v['nickname'] = HelperService::wxNickNameFormat($userDatas[$v['user_id']]['nickname']);
                } else {
                    $v['user_code'] = '';
                    $v['nickname'] = '';
                }
            }

            $sumCoin += $v['change_money'];
            $v['user_money'] = $v['change_money'];
            $v['change_time'] = $v['created_at'];

            // 名字等号的问题处理
            if ($v['nickname'] && strpos($v['nickname'], '=') === 0) {
                $v['nickname'] = "'" . $v['nickname'];
            }
            // 清除多余数据
            unset($v['source_id']);
            unset($v['room_id']);
            unset($v['arr_type']);
            unset($v['gift_user']);
            unset($v['change_type']);
        }


        return $data;
    }
}
